package org.example;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 演示将一个复杂对象(包含另一个复杂对象)转换为JSON字符串
 */
public class AppSerializeObject2Json {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        try {
            // 1. 创建 ObjectMapper 实例 (通常可以全局单例)
            ObjectMapper mapper = new ObjectMapper();

            // 2. 创建一个 Java 对象
            Person person = new Person("张三", 30);


            System.out.println("直接打印原始person信息:"+person);

            // 3. 将对象序列化为 JSON 字符串
            String jsonStringWithoutEmail = mapper.writeValueAsString(person);

            // 4. 输出结果
            System.out.println(jsonStringWithoutEmail);
            //输出: {"name":"张三","age":30,"email":null}

            person.setEmail(new Email("zs@company.com", "工作中常用邮箱"));

            String jsonStringWithEmail = mapper.writeValueAsString(person);
            System.out.println(jsonStringWithEmail);

            person.setHobbies(new Hobby[]{new PlayPingPong(), new PlayComputer()});
            System.out.println(person);
            System.out.println(mapper.writeValueAsString(person));

            System.out.println("----------------------------------------------------------");

            // 将其转为 Object 对象时,依然可以正常地序列化为 json 字符串
            Object toObject =(Object) person;

            String toObjectString = mapper.writeValueAsString(toObject);

            System.out.println("toObjectString:"+toObjectString);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
